﻿using System;
using System.Linq;
using Model;

namespace BusinessObject
{
    public class UserBO : Repository<User>
    {
        #region Singleton

        private static readonly UserBO _instance = new UserBO();

        /// <summary>
        /// Instância do objeto singleton.
        /// </summary>
        public static UserBO Instance
        {
            get { return _instance; }
        }

        private UserBO() { }

        #endregion Singleton

        public User RecoverUser(string login, string password)
        {
            return base.GetByCriteria(user => user.Login == login && user.Senha == password).FirstOrDefault();
        }

        public void ChangePassword(string oldPassword, string newPassword, User user)
        {
            try
            {
                if (user.Senha == oldPassword)
                {
                    user.Senha = newPassword;
                    UserBO.Instance.Update(user);
                }
                else
                {
                    throw new Exception("Senha passada n&atilde;o confere com a cadastrada.");
                }
            }
            catch (Exception e)
            {
                throw e;
            }
        }

        public bool InsertUser(string login, string password, string email, string name, string perfil)
        {
            if (UserBO.Instance.GetByCriteria(l => l.Login == login).Count == 0)
            {
                User user = new User();
                user.Login = login;
                user.Senha = password;
                user.Email = email;
                user.Nome = name;
                user.Perfil = PerfilBO.Instance.getByName(perfil);

                try
                {
                    UserBO.Instance.Save(user);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
    }
}